//
//  HomeView.swift
//  CMB250716
//
//  Created by Andy Lau on 16/7/25.
//

import SwiftUI
import Foundation
import UIKit
import ImageIO

struct HomeView: View {
    @EnvironmentObject var dataManager: DataManager
    @State private var showingCouponsView = false
    @State private var showingShareSheet = false
    @State private var showingInviteView = false
    @State private var selectedCoupon: Coupon?
    @State private var showingVoucherDetail = false
    @State private var showingMenuView = false
    @Binding var selectedTab: Int
    @Environment(\.colorScheme) var colorScheme
    
    // MARK: - MenuItem对象定义
    private var koreanFriedChickenSetItem: MenuItem {
        MenuItem(
            name: AppStrings.Menu.koreanFriedChickenSet,
            englishName: AppStrings.Menu.koreanFriedChickenSetEn,
            description: AppStrings.Menu.crispyOutsideTenderInside,
            englishDescription: AppStrings.Menu.crispyOutsideTenderInsideEn,
            price: 59.00,
            category: .combo,
            imageName: "Korean_Fried_Chicken_Set",
            realImageName: "Korean_Fried_Chicken_Set"
        )
    }
    
    private var tripleDelightDesertItem: MenuItem {
        MenuItem(
            name: "Triple Delight Desert",
            englishName: "Triple Delight Desert",
            description: "豆浆、巧克力和草莓",
            englishDescription: "Soya Milk, Chocolate & Strawberry",
            price: 8.80,
            category: .recommended,
            imageName: "MainPIceC",
            realImageName: "MainPIceC"
        )
    }
    
    private var refreshingHighballCocktailsItem: MenuItem {
        MenuItem(
            name: "清爽Highball鸡尾酒",
            englishName: "refreshing Highball cocktails",
            description: AppStrings.Menu.perfectAfternoonCombo,
            englishDescription: AppStrings.Menu.perfectAfternoonComboEn,
            price: 5.00,
            category: .drinks,
            imageName: "HighBallMpage",
            realImageName: "HighBallMpage"
        )
    }
    
    var body: some View {
        ZStack {
            // 背景图片
            Image("HomeBackground")
                .resizable()
                .scaledToFill()
                .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
                .clipped()
                .ignoresSafeArea(.all)
            
            // 主要内容
            ScrollView {
                VStack(spacing: 16) {
                    // 优惠券区域
                    couponsSection
                    
                    // 今日推荐
                    todayRecommendedSection
                    
                    // 现金券推广
                    cashVoucherSection
                    
                    // 限时半价优惠卡片
                    limitedTimeDiscountSection
                    
                    // 分享赢积分
                    sharePointsSection
                    
                    // 社交媒体图标
                    socialMediaSection
                    
                    // 版权信息
                    copyrightSection
                }
                .padding(.horizontal, 10)
                .padding(.top, AppTheme.Dimensions.homeTopPadding)
                .padding(.bottom, 20)
            }
        }
        .navigationBarHidden(true)
        .sheet(item: $selectedCoupon) { coupon in
            if #available(iOS 16.0, *) {
                CouponDetailSheet(coupon: coupon)
                    .environmentObject(dataManager)
            } else {
                // Fallback for iOS 15
                Text("详细信息")
                    .padding()
            }
        }

        .sheet(isPresented: $showingVoucherDetail) {
            VoucherDetailSheet()
                .environmentObject(dataManager)
        }
        .onChange(of: showingMenuView) { newValue in
            if newValue {
                selectedTab = 1 // 切换到菜单标签页
                showingMenuView = false
            }
        }
        // 购物车冲突alert已移除，现在使用自动替换逻辑
    }
    

    
    // MARK: - 优惠券区域
    private var couponsSection: some View {
        VStack(alignment: .leading, spacing: AppTheme.Dimensions.homeSectionInternalSpacing) {
            HStack {
                ZStack {
                    Circle()
                        .fill(
                            LinearGradient(
                                colors: [
                                    Color(red: 1.0, green: 0.6, blue: 0.2),
                                    Color(red: 1.0, green: 0.5, blue: 0.1)
                                ],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                        .frame(width: 24, height: 24)
                    
                    Image(systemName: "ticket.fill")
                        .font(.system(size: 12, weight: .medium))
                        .foregroundColor(.white)
                }
                
                Text(dataManager.currentLanguage == "zh" ? AppStrings.Coupons.availableCoupons : "Limited Coupons")
                    .font(AppTheme.Typography.headline)
                    .foregroundColor(AppTheme.Colors.primaryText)
                
                Spacer()
                
                Button(action: {
                    showingCouponsView = true
                }) {
                    HStack(spacing: 4) {
                        Text(dataManager.currentLanguage == "zh" ? AppConfig.UIText.viewAllText.chinese : AppConfig.UIText.viewAllText.english)
                            .font(AppTheme.Typography.caption)
                            .foregroundColor(.white)
                        
                        Image(systemName: "chevron.right")
                            .font(AppTheme.Typography.caption)
                            .foregroundColor(.white)
                    }
                    .padding(.horizontal, 8)
                    .padding(.vertical, 4)
                    .background(
                        RoundedRectangle(cornerRadius: AppConfig.UIText.cloudBackgroundConfig.cornerRadius)
                            .fill(
                                Color(red: AppConfig.ColorConfig.cloudBackground.red,
                                      green: AppConfig.ColorConfig.cloudBackground.green,
                                      blue: AppConfig.ColorConfig.cloudBackground.blue)
                                .opacity(AppConfig.UIText.cloudBackgroundConfig.opacity)
                            )
                            .shadow(
                                color: Color.black.opacity(0.3),
                                radius: AppConfig.UIText.cloudBackgroundConfig.shadowRadius,
                                x: 0,
                                y: 2
                            )
                    )
                }
            }
            
            ScrollView(.horizontal, showsIndicators: false) {
                LazyHStack(spacing: 10) {
                    // 使用与All Coupons相同的排序数据源，确保数据统一
                    ForEach(dataManager.getSortedAvailableCoupons().prefix(10), id: \.code) { coupon in
                        CouponCardView(coupon: coupon) {
                            selectedCoupon = coupon
                        }
                        .frame(width: 280, height: 76)
                        .fixedSize(horizontal: true, vertical: true)
                    }
                }
                .padding(.leading, 0)
                .padding(.trailing, 16)
            }
        }
        .sheet(isPresented: $showingCouponsView) {
            if #available(iOS 16.0, *) {
                CouponsView()
                    .environmentObject(dataManager)
                    .presentationDetents([.fraction(0.67), .large])
            } else {
                CouponsView()
                    .environmentObject(dataManager)
            }
        }
    }
    
    // MARK: - 今日推荐
    private var todayRecommendedSection: some View {
        VStack(alignment: .leading, spacing: AppTheme.Dimensions.homeSectionInternalSpacing) {
            HStack {
                ZStack {
                    Circle()
                        .fill(
                            LinearGradient(
                                colors: [
                                    Color.yellow,
                                    Color.orange
                                ],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                        .frame(width: 24, height: 24)
                    
                    Image(systemName: "star.fill")
                        .font(.system(size: 12, weight: .medium))
                        .foregroundColor(.white)
                }
                
                Text(dataManager.currentLanguage == "zh" ? "今日推荐" : "Today's Recommendations")
                    .font(AppTheme.Typography.headline)
                    .foregroundColor(AppTheme.Colors.primaryText)
                
                Spacer()
                
                Button(action: {
                    selectedTab = 1 // 切换到菜单标签页
                }) {
                    HStack(spacing: 4) {
                        Text(dataManager.currentLanguage == "zh" ? "查看更多" : "View More")
                            .font(AppTheme.Typography.caption)
                            .foregroundColor(.white)
                        
                        Image(systemName: "chevron.right")
                            .font(AppTheme.Typography.caption)
                            .foregroundColor(.white)
                    }
                    .padding(.horizontal, 8)
                    .padding(.vertical, 4)
                    .background(
                        RoundedRectangle(cornerRadius: AppConfig.UIText.cloudBackgroundConfig.cornerRadius)
                            .fill(
                                Color(red: AppConfig.ColorConfig.cloudBackground.red,
                                      green: AppConfig.ColorConfig.cloudBackground.green,
                                      blue: AppConfig.ColorConfig.cloudBackground.blue)
                                .opacity(AppConfig.UIText.cloudBackgroundConfig.opacity)
                            )
                            .shadow(
                                color: Color.black.opacity(0.3),
                                radius: AppConfig.UIText.cloudBackgroundConfig.shadowRadius,
                                x: 0,
                                y: 2
                            )
                    )
                }
            }
            
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: 10) {
                    // 韩式炸鸡套餐
                    VStack(alignment: .leading, spacing: 0) {
                        // 图片区域
                        ZStack {
                            // 使用新的图片组件，支持真实图片
                            MenuItemImageView(
                                imageSource: .local("Korean_Fried_Chicken_Set"),
                                height: 120,
                                cornerRadius: 16
                            )
                            .overlay(
                                // 渐变遮罩，确保文字可见
                                LinearGradient(
                                    colors: [
                                        Color.clear,
                                        Color.black.opacity(0.3)
                                    ],
                                    startPoint: .top,
                                    endPoint: .bottom
                                )
                                .cornerRadius(16)
                            )
                            
                            // 折扣标签
                            VStack {
                                HStack {
                                    Spacer()
                                    
                                    Text("20% OFF")
                                        .font(.caption2)
                                        .fontWeight(.bold)
                                        .foregroundColor(.white)
                                        .padding(.horizontal, 8)
                                        .padding(.vertical, 4)
                                        .background(
                                            Capsule()
                                                .fill(Color.red)
                                        )
                                }
                                
                                Spacer()
                            }
                            .padding(12)
                        }
                        
                        VStack(alignment: .leading, spacing: 8) {
                            Text(dataManager.currentLanguage == "zh" ? AppStrings.Menu.koreanFriedChickenSet : AppStrings.Menu.koreanFriedChickenSetEn)
                                .font(AppTheme.Typography.headline)
                                .fontWeight(.bold)
                                .foregroundColor(AppTheme.Colors.primaryText)
                                .lineLimit(2)
                            
                            Text(dataManager.currentLanguage == "zh" ? AppStrings.Menu.crispyOutsideTenderInside : AppStrings.Menu.crispyOutsideTenderInsideEn)
                                .font(AppTheme.Typography.caption)
                                .foregroundColor(AppTheme.Colors.secondaryText)
                                .lineLimit(2)
                            
                            HStack {
                                VStack(alignment: .leading, spacing: 2) {
                                    Text("S$59.00")
                                        .font(AppTheme.Typography.title3)
                                        .fontWeight(.bold)
                                        .foregroundColor(AppTheme.Colors.accent)
                                    
                                    Text("S$73.50")
                                        .font(AppTheme.Typography.caption)
                                        .strikethrough()
                                        .foregroundColor(AppTheme.Colors.secondaryText)
                                }
                                
                                Spacer()
                                
                                Button(action: {
                                    dataManager.addToCart(koreanFriedChickenSetItem)
                                }) {
                                    Image(systemName: "plus.circle.fill")
                                        .font(.title2)
                                        .foregroundColor(.yellow)
                                }
                            }
                        }
                        .padding(16)
                    }
                    .frame(width: 280)
                    .background(
                        RoundedRectangle(cornerRadius: 20)
                            .fill(
                            Color(red: 0.15, green: 0.15, blue: 0.25)
                        )
                            .overlay(
                                RoundedRectangle(cornerRadius: 20)
                                    .stroke(
                                        LinearGradient(
                                            colors: [
                                                Color.white.opacity(0.2),
                                                Color.white.opacity(0.05)
                                            ],
                                            startPoint: .topLeading,
                                            endPoint: .bottomTrailing
                                        ),
                                        lineWidth: 1
                                    )
                            )
                    )
                
                    // TRIPLE DELIGHT DESERT
                    VStack(alignment: .leading, spacing: 0) {
                        // 图片区域
                        ZStack {
                            // 使用新的图片组件，支持真实图片
                            MenuItemImageView(
                                imageSource: .local("MainPIceC"),
                                height: 120,
                                cornerRadius: 16
                            )
                            .overlay(
                                // 渐变遮罩，确保文字可见
                                LinearGradient(
                                    colors: [
                                        Color.clear,
                                        Color.black.opacity(0.3)
                                    ],
                                    startPoint: .top,
                                    endPoint: .bottom
                                )
                                .cornerRadius(16)
                            )
                            

                        }
                        
                        VStack(alignment: .leading, spacing: 8) {
                            Text(dataManager.currentLanguage == "zh" ? "Triple Delight Desert" : "Triple Delight Desert")
                                .font(AppTheme.Typography.headline)
                                .fontWeight(.bold)
                                .foregroundColor(AppTheme.Colors.primaryText)
                                .lineLimit(2)
                            
                            Text(dataManager.currentLanguage == "zh" ? "豆浆、巧克力和草莓" : "Soya Milk, Chocolate & Strawberry")
                                .font(AppTheme.Typography.caption)
                                .foregroundColor(AppTheme.Colors.secondaryText)
                                .lineLimit(2)
                            
                            HStack {
                                VStack(alignment: .leading, spacing: 2) {
                                    Text("S$8.80")
                                        .font(AppTheme.Typography.title3)
                                        .fontWeight(.bold)
                                        .foregroundColor(AppTheme.Colors.accent)
                                    
                                    Text("S$12.60")
                                        .font(AppTheme.Typography.caption)
                                        .strikethrough()
                                        .foregroundColor(AppTheme.Colors.secondaryText)
                                }
                                
                                Spacer()
                                
                                Button(action: {
                                    dataManager.addToCart(tripleDelightDesertItem)
                                }) {
                                    Image(systemName: "plus.circle.fill")
                                        .font(.title2)
                                        .foregroundColor(.yellow)
                                }
                            }
                        }
                        .padding(16)
                    }
                    .frame(width: 280)
                    .background(
                        RoundedRectangle(cornerRadius: 20)
                            .fill(
                            Color(red: 0.15, green: 0.15, blue: 0.25)
                        )
                            .overlay(
                                RoundedRectangle(cornerRadius: 20)
                                    .stroke(
                                        LinearGradient(
                                            colors: [
                                                Color.white.opacity(0.2),
                                                Color.white.opacity(0.05)
                                            ],
                                            startPoint: .topLeading,
                                            endPoint: .bottomTrailing
                                        ),
                                        lineWidth: 1
                                    )
                            )
                    )
                
                    // refreshing Highball cocktails
                    VStack(alignment: .leading, spacing: 0) {
                        // 图片区域
                        ZStack {
                            // 使用新的图片组件，支持真实图片
                            MenuItemImageView(
                                imageSource: .local("HighBallMpage"),
                                height: 120,
                                cornerRadius: 16
                            )
                            .overlay(
                                // 渐变遮罩，确保文字可见
                                LinearGradient(
                                    colors: [
                                        Color.clear,
                                        Color.black.opacity(0.3)
                                    ],
                                    startPoint: .top,
                                    endPoint: .bottom
                                )
                                .cornerRadius(16)
                            )
                            
                            // Limited Time标签
                            VStack {
                                HStack {
                                    Spacer()
                                    
                                    Text(dataManager.currentLanguage == "zh" ? "限时优惠" : "Limited Time")
                                        .font(.caption2)
                                        .fontWeight(.bold)
                                        .foregroundColor(.white)
                                        .padding(.horizontal, 8)
                                        .padding(.vertical, 4)
                                        .background(
                                            Capsule()
                                                .fill(Color.orange)
                                        )
                                }
                                
                                Spacer()
                            }
                            .padding(12)
                        }
                        
                        VStack(alignment: .leading, spacing: 8) {
                            Text(dataManager.currentLanguage == "zh" ? "清爽Highball鸡尾酒" : "refreshing Highball cocktails")
                                .font(AppTheme.Typography.headline)
                                .fontWeight(.bold)
                                .foregroundColor(AppTheme.Colors.primaryText)
                                .lineLimit(2)
                            
                            Text(dataManager.currentLanguage == "zh" ? AppStrings.Menu.perfectAfternoonCombo : AppStrings.Menu.perfectAfternoonComboEn)
                                .font(AppTheme.Typography.caption)
                                .foregroundColor(AppTheme.Colors.secondaryText)
                                .lineLimit(2)
                            
                            HStack {
                                VStack(alignment: .leading, spacing: 2) {
                                    Text("S$5.00")
                                        .font(AppTheme.Typography.title3)
                                        .fontWeight(.bold)
                                        .foregroundColor(AppTheme.Colors.accent)
                                    
                                    Text("S$10.00")
                                        .font(AppTheme.Typography.caption)
                                        .strikethrough()
                                        .foregroundColor(AppTheme.Colors.secondaryText)
                                }
                                
                                Spacer()
                                
                                Button(action: {
                                    dataManager.addToCart(refreshingHighballCocktailsItem)
                                }) {
                                    Image(systemName: "plus.circle.fill")
                                        .font(.title2)
                                        .foregroundColor(.yellow)
                                }
                            }
                        }
                        .padding(16)
                    }
                    .frame(width: 280)
                    .background(
                        RoundedRectangle(cornerRadius: 20)
                            .fill(
                            LinearGradient(
                                colors: [
                                    Color(red: 0.12, green: 0.12, blue: 0.12),
                                    Color(red: 0.18, green: 0.16, blue: 0.15)
                                ],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                            .overlay(
                                RoundedRectangle(cornerRadius: 20)
                                    .stroke(
                                        LinearGradient(
                                            colors: [
                                                Color.white.opacity(0.2),
                                                Color.white.opacity(0.05)
                                            ],
                                            startPoint: .topLeading,
                                            endPoint: .bottomTrailing
                                        ),
                                        lineWidth: 1
                                    )
                            )
                    )
                }
                .padding(.horizontal, 2)
            }
        }
    }
    
    // MARK: - 分享赢积分
    private var sharePointsSection: some View {
        VStack(alignment: .leading, spacing: 4) {
            // 卡片标题 - 放在卡片上方靠左
            HStack {
                Text(dataManager.currentLanguage == "zh" ? AppStrings.Promotion.shareCardTitle : AppStrings.Promotion.shareCardTitleEn)
                    .font(AppTheme.Typography.bodyMedium)
                    .fontWeight(.semibold)
                    .foregroundColor(AppTheme.Colors.primaryText)
                Spacer()
            }
            
            // 卡片内容 - Share & Earn视频
            Button(action: {
                showingInviteView = true
            }) {
                MP4VideoView(videoName: "SharenEarnVideo")
                    .frame(height: 115)
                    .frame(maxWidth: .infinity)
                    .background(Color.black) // 添加黑色背景消除白色空隙
                    .clipped()
                    .cornerRadius(15)
            }
            .buttonStyle(PlainButtonStyle())
            .frame(maxWidth: .infinity)
            .sheet(isPresented: $showingInviteView) {
                if #available(iOS 16.0, *) {
                    InviteView()
                        .environmentObject(dataManager)
                        .presentationDetents([.fraction(AppConfig.UI.inviteViewHeightFraction)])
                } else {
                    InviteView()
                        .environmentObject(dataManager)
                }
            }
        }
    }
    
    // MARK: - 现金券推广
    private var cashVoucherSection: some View {
        VStack(alignment: .leading, spacing: AppTheme.Dimensions.homeSectionInternalSpacing) {
            HStack {
                // 左侧图标和文字，靠左对齐
                HStack(spacing: 8) {
                    Image(systemName: "dollarsign.circle.fill")
                        .foregroundColor(.orange)
                        .font(.title2)
                    Text("Cash Voucher")
                        .font(.headline)
                        .fontWeight(.bold)
                        .foregroundColor(.white)
                }
                
                Spacer()
                
                // 右侧View Details按钮
                Button(action: {
                    showingVoucherDetail = true
                }) {
                    HStack(spacing: 4) {
                        Text(dataManager.currentLanguage == "zh" ? AppStrings.Common.viewDetails : AppStrings.Common.viewDetailsEn)
                            .font(AppTheme.Typography.caption)
                            .fontWeight(.bold)
                            .foregroundColor(AppTheme.Colors.accent)
                        
                        Image(systemName: "chevron.right")
                            .font(.caption.bold())
                            .foregroundColor(Color(red: 1.0, green: 0.84, blue: 0.0))
                    }
                }
            }
            
            // MP4 Video Player - 全宽度显示，添加点击事件
            Button(action: {
                showingVoucherDetail = true
            }) {
                MP4VideoView(videoName: "CashVoucherVideo")
                    .frame(height: 120)
                    .frame(maxWidth: .infinity)
                    .cornerRadius(15)
                    .overlay(
                        RoundedRectangle(cornerRadius: 15)
                            .stroke(
                                LinearGradient(
                                    gradient: Gradient(colors: [
                                        Color(red: 1.0, green: 0.84, blue: 0.0), // 金色
                                        Color(red: 0.8, green: 0.6, blue: 0.0),  // 深金色
                                        Color.black.opacity(0.8)                  // 黑色
                                    ]),
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                ),
                                lineWidth: 0.7
                            )
                    )
                    .shadow(
                        color: Color(red: 1.0, green: 0.84, blue: 0.0).opacity(0.6),
                        radius: 8,
                        x: 0,
                        y: 4
                    )
            }
            .buttonStyle(PlainButtonStyle())
            .shadow(
                color: Color.black.opacity(0.3),
                radius: 12,
                x: 0,
                y: 8
            )
        }
        .padding(.horizontal, 0)
    }
    
    // MARK: - 限时半价优惠
    private var limitedTimeDiscountSection: some View {
        VStack(alignment: .leading, spacing: AppTheme.Dimensions.homeSectionInternalSpacing) {
            HStack {
                // 左侧图标和文字，靠左对齐
                HStack(spacing: 8) {
                    Image(systemName: "clock.fill")
                        .foregroundColor(.orange)
                        .font(.title2)
                    Text("Limited Time 50% OFF")
                        .font(.headline)
                        .fontWeight(.bold)
                        .foregroundColor(.white)
                }
                
                Spacer()
                
                // 右侧View Details按钮
                Button(action: {
                    selectedTab = 1 // 切换到菜单标签页
                }) {
                    HStack(spacing: 4) {
                        Text(dataManager.currentLanguage == "zh" ? "查看更多" : "View More")
                            .font(AppTheme.Typography.caption)
                            .fontWeight(.bold)
                            .foregroundColor(AppTheme.Colors.accent)
                        
                        Image(systemName: "chevron.right")
                            .font(.caption.bold())
                            .foregroundColor(Color(red: 1.0, green: 0.84, blue: 0.0))
                    }
                }
            }
            
            // MP4 Video Player - 全宽度显示，添加点击事件
            Button(action: {
                selectedTab = 1 // 切换到菜单标签页
            }) {
                MP4VideoView(videoName: "50offVedio")
                    .frame(height: 120)
                    .frame(maxWidth: .infinity)
                    .cornerRadius(15)
                    .overlay(
                        RoundedRectangle(cornerRadius: 15)
                            .stroke(
                                LinearGradient(
                                    gradient: Gradient(colors: [
                                        Color(red: 1.0, green: 0.84, blue: 0.0), // 金色
                                        Color(red: 0.8, green: 0.6, blue: 0.0),  // 深金色
                                        Color.black.opacity(0.8)                  // 黑色
                                    ]),
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                ),
                                lineWidth: 0.7
                            )
                    )
                    .shadow(
                        color: Color(red: 1.0, green: 0.84, blue: 0.0).opacity(0.6),
                        radius: 8,
                        x: 0,
                        y: 4
                    )
            }
            .buttonStyle(PlainButtonStyle())
            .shadow(
                color: Color.black.opacity(0.3),
                radius: 12,
                x: 0,
                y: 8
            )
        }
        .padding(.horizontal, 0)
    }
    
    // MARK: - 社交媒体图标
    private var socialMediaSection: some View {
        VStack(spacing: 16) {
            // 社交媒体图标行
            HStack(spacing: 32) {
                ForEach(SocialMediaManager.homePagePlatforms, id: \.self) { platform in
                    Button(action: {
                        SocialMediaManager.openSocialMedia(platform: platform)
                    }) {
                        Image(platform.iconName)
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .frame(width: 38.4, height: 38.4) // 48 * 0.8 = 38.4
                    }
                    .buttonStyle(PlainButtonStyle())
                }
            }
            .padding(.horizontal, 20)
        }
        .padding(.vertical, 16)
    }
    
    // MARK: - 版权信息
    private var copyrightSection: some View {
        VStack(spacing: 12) {
            Divider()
                .background(Color.white.opacity(0.2))
            
            VStack(spacing: 6) {
                HStack(spacing: 8) {
                    Image(systemName: "c.circle")
                        .font(.caption)
                        .foregroundColor(.white.opacity(0.6))
                    
                    Text(AppStrings.Common.copyright)
                    .font(AppTheme.Typography.caption)
                    .foregroundColor(AppTheme.Colors.secondaryText)
                }
            }
        }
        .padding(.vertical, 20)
        .padding(.horizontal, 20)
    }
    

}

// MARK: - 优惠券卡片
struct CouponCardView: View {
    let coupon: Coupon
    let onButtonTap: () -> Void
    @EnvironmentObject var dataManager: DataManager
    
    // 检查优惠券激活状态 - 使用统一的解锁条件检查
    private func checkCouponActivation(coupon: Coupon) -> CouponStatus {
        let unlockCondition = CouponConfig.UnlockConditions.getUnlockConditionType(
            for: coupon.code,
            user: dataManager.currentUser,
            dataManager: dataManager
        )
        
        switch unlockCondition {
        case .loginRequired:
            return .requiresLogin
        case .membershipLevel(_):
            return .requiresMembershipLevel
        case .timeSlotRestricted:
            return .outsideTimeSlot
        case .memberInfoComplete, .birthdayMonthRequired, .activationConditions(_), .expired, .inactive:
            return .notActivated
        case .usageLimitReached:
            return .usedOnce
        case .usageFrequencyReached:
            return .usedThisWeek // 默认返回周使用状态
        case .none:
            return .available
        }
    }
    
    // 优惠券状态枚举
    enum CouponStatus {
        case available
        case expired
        case usedOnce
        case usedThisWeek
        case usedToday
        case usedThisMonth
        case usedThisYear
        case outsideTimeSlot
        case notActivated
        case requiresLogin
        case requiresMembershipLevel
    }
    
    var body: some View {
        let isCashVoucher = coupon.isCashVoucher
        let displayTitle = coupon.formattedTitle(language: dataManager.currentLanguage)
        let _ = isCashVoucher ? dataManager.getCashVoucherQuantity(for: displayTitle) : nil
        
        // 检查用户是否已解锁此优惠券
        let isUnlocked = dataManager.isUserCouponUnlocked(coupon)
        
        // 检查激活状态
        let activationStatus = checkCouponActivation(coupon: coupon)
        let isNotActivated = activationStatus != .available
        
        // 检查会员信息完善礼券的特殊状态
        let isMemberInfoCoupon = coupon.code == "MEMBER_INFO_COMPLETE"
        let isDisabled = isMemberInfoCoupon && !(dataManager.currentUser?.isMemberInfoComplete ?? false)
        let hasUserCoupon = dataManager.currentUser?.ownedCoupons.contains { $0.couponCode == coupon.code && !$0.isUsed && $0.expiryDate > Date() } ?? false
        
        // 检查是否因为非运营时间而被限制
        let isTimeSlotRestricted = activationStatus == .outsideTimeSlot
        
        // 如果是会员信息完善礼券且用户已拥有，则显示为可用状态
        // 如果用户未解锁此优惠券，则显示为禁用状态
        // 但如果仅仅是因为非运营时间限制，则在视觉上不显示为禁用状态
        let finalDisabled = !isUnlocked || (isMemberInfoCoupon ? (!hasUserCoupon && isDisabled) : (isNotActivated && !isTimeSlotRestricted))
        
        let baseCard = HStack(alignment: .center, spacing: 10) {
            VStack(alignment: .leading, spacing: 4) {
                Text(coupon.formattedTitle(language: dataManager.currentLanguage))
                    .font(.caption2)
                    .fontWeight(.bold)
                    .foregroundColor(CouponTheme.getTagTextColor(for: coupon.title))
                    .lineLimit(1)
                    .truncationMode(.tail)
                    .padding(.horizontal, 5)
                    .padding(.vertical, 2)
                    .background(Capsule().fill(CouponTheme.getTagBackgroundColor(for: coupon.title)))
                
                Text(" " + coupon.formattedRemarks(language: dataManager.currentLanguage, displayTitle: coupon.formattedTitle(language: dataManager.currentLanguage)))
                    .font(.caption2)
                    .fontWeight(.medium)
                    .foregroundColor(.white)
                    .lineLimit(1)
                    .truncationMode(.tail)
            }
            
            Spacer()
            
            VStack(alignment: .trailing, spacing: 4) {
                Text(coupon.discountType == .percentage ? "\(Int(coupon.discountValue))%" : "S$\(coupon.discountValue, specifier: "%.0f")")
                    .font(.subheadline)
                    .fontWeight(.bold)
                    .foregroundColor(.white)
                
                Button(action: onButtonTap) {
                    Text(dataManager.currentLanguage == "zh" ? "查看详情" : "View Details")
                        .font(.caption2)
                        .fontWeight(.bold)
                        .foregroundColor(CouponTheme.getButtonTextColor(for: coupon.title))
                        .padding(.horizontal, 8)
                        .padding(.vertical, 3)
                        .background(
                            Capsule()
                                .fill(CouponTheme.getButtonBackgroundColor(for: coupon.title))
                        )
                }
            }
        }
        .padding(8)
        .background(
            ZStack {
                // 主背景渐变
                RoundedRectangle(cornerRadius: 12)
                    .fill(
                        LinearGradient(
                            colors: CouponTheme.getGradientColors(for: coupon.title),
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                
                // 边框渐变
                RoundedRectangle(cornerRadius: 12)
                    .stroke(
                        LinearGradient(
                            colors: [
                                Color.white.opacity(0.3),
                                Color.clear,
                                Color.black.opacity(0.1)
                            ],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        ),
                        lineWidth: 1
                    )
                
                // 内部高光
                RoundedRectangle(cornerRadius: 11)
                    .fill(
                        LinearGradient(
                            colors: [
                                Color.white.opacity(0.15),
                                Color.clear
                            ],
                            startPoint: .top,
                            endPoint: .center
                        )
                    )
                    .padding(1)
            }
            .shadow(color: .black.opacity(0.2), radius: 6, x: 0, y: 3)
            .shadow(color: .black.opacity(0.1), radius: 2, x: 0, y: 1)
        )
        
        // 应用锁定状态的视觉效果
        Group {
            if finalDisabled {
                ZStack {
                    baseCard
                        .opacity(0.6)
                        .overlay(
                            RoundedRectangle(cornerRadius: 12)
                                .fill(Color.black.opacity(0.4))
                        )
                    
                    // 锁定图标和文本
                    VStack(spacing: 4) {
                        Image(systemName: "lock.fill")
                            .font(.title2)
                            .foregroundColor(.white)
                        
                        Text({
                            if !isUnlocked {
                                return dataManager.currentLanguage == "zh" ? "需要解锁" : "Requires Unlock"
                            } else {
                                switch activationStatus {
                                case .outsideTimeSlot:
                                     return dataManager.currentLanguage == "zh" ? "不在运营时间，无法应用" : "Outside Business Hours"
                                case .requiresLogin:
                                    return dataManager.currentLanguage == "zh" ? "需要登录" : "Login Required"
                                case .requiresMembershipLevel:
                                    return dataManager.currentLanguage == "zh" ? "需要会员等级" : "Membership Required"
                                case .expired:
                                    return dataManager.currentLanguage == "zh" ? "优惠券已过期" : "Coupon Expired"
                                case .usedOnce, .usedThisWeek, .usedToday, .usedThisMonth, .usedThisYear:
                                    // 检查是否为perOrder类型的优惠券
                                    if activationStatus == .usedOnce,
                                       coupon.usageFrequency == .perOrder {
                                        return dataManager.currentLanguage == "zh" ? "已用，明日会再激活" : "Used, will reactivate tomorrow"
                                    } else {
                                        return dataManager.currentLanguage == "zh" ? "已使用" : "Already Used"
                                    }
                                default:
                                    return dataManager.currentLanguage == "zh" ? "未激活" : "Not Activated"
                                }
                            }
                        }())
                            .font(.caption2)
                            .fontWeight(.bold)
                            .foregroundColor(.white)
                            .multilineTextAlignment(.center)
                    }
                    .padding(8)
                    .background(
                        RoundedRectangle(cornerRadius: 8)
                            .fill(Color.black.opacity(0.7))
                    )
                }
            } else {
                baseCard
            }
        }
        .onTapGesture {
            onButtonTap()
        }
    }
}

// MARK: - 菜品卡片
struct MenuItemCardView: View {
    let item: MenuItem
    @EnvironmentObject var dataManager: DataManager
    
    var body: some View {
        VStack(alignment: .leading, spacing: 10) {
            // 菜品图片
            RoundedRectangle(cornerRadius: 8)
                .fill(Color(red: 0.3, green: 0.3, blue: 0.3))
                .frame(width: 150, height: 100)
                .overlay(
                    Image(systemName: "photo")
                        .font(.title)
                        .foregroundColor(.gray)
                )
            
            VStack(alignment: .leading, spacing: 5) {
                Text(dataManager.currentLanguage == "zh" ? item.name : item.englishName)
                    .font(.subheadline)
                    .fontWeight(.medium)
                    .foregroundColor(.white)
                    .lineLimit(2)
                
                Text("S$\(item.price, specifier: "%.2f")")
                    .font(.headline)
                    .fontWeight(.bold)
                    .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
            }
            
            Button(action: {
                dataManager.addToCart(item)
            }) {
                Text(dataManager.currentLanguage == "zh" ? "加入购物车" : "Add to Cart")
                    .font(.caption)
                    .foregroundColor(Color(red: 0.12, green: 0.12, blue: 0.12))
                    .padding(.horizontal, 12)
                    .padding(.vertical, 6)
                    .background(
                        RoundedRectangle(cornerRadius: 6)
                            .fill(Color(red: 1.0, green: 0.6, blue: 0.2))
                    )
            }
        }
        .padding(12)
        .frame(width: 150)
        .background(
            RoundedRectangle(cornerRadius: 12)
                .fill(Color(red: 0.2, green: 0.2, blue: 0.2))
        )
    }
}

// MARK: - 促销横幅
struct PromotionBannerView: View {
    let item: MenuItem
    @EnvironmentObject var dataManager: DataManager
    
    var body: some View {
        HStack(spacing: 15) {
            // 菜品图片
            RoundedRectangle(cornerRadius: 8)
                .fill(Color(red: 0.3, green: 0.3, blue: 0.3))
                .frame(width: 80, height: 60)
                .overlay(
                    Image(systemName: "photo")
                        .foregroundColor(.gray)
                )
            
            VStack(alignment: .leading, spacing: 5) {
                Text(dataManager.currentLanguage == "zh" ? item.name : item.englishName)
                    .font(.headline)
                    .foregroundColor(.white)
                
                Text(item.description)
                    .font(.caption)
                    .foregroundColor(.gray)
                    .lineLimit(2)
                
                Text("S$\(item.price, specifier: "%.2f")")
                    .font(.title3)
                    .fontWeight(.bold)
                    .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
            }
            
            Spacer()
            
            Button(action: {
                dataManager.addToCart(item)
            }) {
                Image(systemName: "plus.circle.fill")
                    .font(.title2)
                    .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
            }
        }
        .padding(15)
        .background(
            RoundedRectangle(cornerRadius: 12)
                .fill(Color(red: 0.2, green: 0.2, blue: 0.2))
                .overlay(
                    RoundedRectangle(cornerRadius: 12)
                        .stroke(Color(red: 1.0, green: 0.6, blue: 0.2).opacity(0.3), lineWidth: 1)
                )
        )
    }
}

// 添加分享功能的UIViewControllerRepresentable
struct ShareSheet: UIViewControllerRepresentable {
    let activityItems: [Any]
    
    func makeUIViewController(context: Context) -> UIActivityViewController {
        let controller = UIActivityViewController(
            activityItems: activityItems,
            applicationActivities: nil
        )
        return controller
    }
    
    func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {
        // 不需要更新
    }
    

}





#Preview {
    HomeView(selectedTab: .constant(0))
        .environmentObject(DataManager.shared)
}